package com.remoter.basic.cluster.support;

import java.util.List;

import com.remoter.basic.bean.support.ConsumerModule;
import com.remoter.basic.bean.support.ProviderModule;
import com.remoter.basic.cluster.ILoadBalance;
import com.remoter.basic.util.Final;

/**
 * @author			koko
 * @date 			2017-08-09 11:29:35
 * @description 	类功能说明
 */
public abstract class AbstractLoadBalance implements ILoadBalance{
	
	protected abstract ProviderModule doSelect(ConsumerModule consumer,List<ProviderModule> providers);
	
	@Override
	public ProviderModule select(ConsumerModule consumerModule,List<ProviderModule> providers){
		if(null == providers || providers.size() == 0){
			return null;
		}
		if(providers.size() == 1){
			return providers.get(0);
		}
		return this.doSelect(consumerModule,providers);
	}
	
	protected int getWeight(ProviderModule provider){
		int weight = provider.getWeight() <= 0 ? Final.D_VAL_PROVIDER_WEIGHT : provider.getWeight();
		if(weight > 0){
			long timestamp = System.currentTimeMillis();
			if(timestamp > 0L){
				int uptime = (int)(System.currentTimeMillis() - timestamp);
				int warmup = (int)provider.getStartTime();
				if(uptime > 0 && uptime < warmup){
					weight = calculateWarmupWeight(uptime, warmup, weight);
				}
			}
		}
		return weight;
	}
	
	protected static int calculateWarmupWeight(int uptime,int warmup,int weight){
		int ww = (int) ( (float) uptime / ( (float) warmup / (float) weight ) );
    	return ww < 1 ? 1 : (ww > weight ? weight : ww);
	}
	
}